<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <link rel="stylesheet" type="text/css" href="http://cache.amap.com/lbs/static/jsDemoStyle20150512.css">
    <title>在线地图绘制</title>  
    <style type="text/css">
        #tip {
            height: 28px;
            background-color: #fff;
            padding-left: 10px;
            padding-right: 10px;
            position: absolute;
            font-size: 12px;
            left: 5px;
            bottom: 2px;
            border-radius: 3px;
            line-height: 30px;
            border: 1px solid #ccc;
            z-index:9999;
        }

        #tip input {
            border: 1px solid #ddd;
            height: 23px;
            border-radius: 3px;
            outline: none;
        }
        
        #operationDiv {
            height: 28px;
            background-color: #fff;
            padding-right: 10px;
            position: absolute;
            font-size: 12px;
            right: 80px;
            top: 10px;
            border-radius: 3px;
            line-height: 30px;
            border: 1px solid #ccc;
        }
        
        #layerIdv {
            height: 128px;
            background-color: #fff;
            padding-left: 10px;
            padding-right: 10px;
            position: absolute;
            font-size: 12px;
            left: 5px;
            bottom: 50px;
            border-radius: 3px;
            line-height: 30px;
            border: 1px solid #ccc;
        }
        
        #layerIdv input{
        	clear:both;
        }
    </style>
    
    <script type="text/javascript" src="js/lib/jquery/jquery.min.js" ></script>
    <script type="text/javascript" src="js/lib/jquery/jquery.json.min.js" ></script>
    <script type="text/javascript" src='mapEditor/MapLatLon.js'></script>
    <script type="text/javascript" src='mapEditor/CoordinateConvert.js'></script>
    <script type="text/javascript" src='mapEditor/MapUtil.js'></script>
    <script type="text/javascript" src='mapEditor/MapColor.js'></script>
    <script type="text/javascript" src='mapEditor/MapCommon.js'></script>
    <script type="text/javascript" src='mapEditor/MapObjExtData.js'></script>
    <script type="text/javascript" src='mapEditor/MapEditor.js'></script>
  </head>
  <body>
    <div id="mapDiv" class="map" tabindex="0"></div>
    <div id="operationDiv">
    	<input type="button" value="保存" onclick='saveAll()'/>
    	<input type="button" value="显示景点" onclick='showAllMarkers()'/>
    	<input type="button" value="隐藏景点" onclick='hideAllMarkers()'/>
    	<input type="button" value="显示名称" onclick='showAllMarkersName()'/>
    	<input type="button" value="隐藏名称" onclick='hideAllMarkersName()'/>
    	<input type="button" value="显示网格" onclick='showAllGrids()'/>
    	<input type="button" value="隐藏网格" onclick='hideAllGrids()'/>
    	<input type="button" value="显示痕迹" onclick='showAllFootTraces()'/>
    	<input type="button" value="隐藏痕迹" onclick='hideAllFootTraces()'/>
    	<!-- 
    	<input type="button" value="加载" onclick='loadAll()'/>
    	 -->
    </div>
    <div id="layerIdv">
    	<table border="1">
    		<thead></thead>
    			<tr><th>显示</th><th>名称</th><th>操作</th><th>类型</th></tr>
    		<tbody>
    			<tr>
    				<td><input type="checkbox" checked onchange='changeVisibleOfPathLayer()' id="pathId"/></td>
    				<td>道路</td>
    				<td><input type="button" value="创建" onclick='startCreatePath()'/>
    					<input type="button" value="开始编辑" onclick='startEditPath()'/>
    					<input type="button" value="结束编辑" onclick='endEditPath()'/>
    					<input type="button" value="删除" onclick='deleteSelectPath()'/>
    					<input type="button" value="全选" onclick='selectAllPath(true)'/>
    					<input type="button" value="清选" onclick='selectAllPath(false)'/>
    					<input type="button" value="上移" onclick='moveUpOfPath(true)'/>
    					<input type="button" value="下移" onclick='moveUpOfPath(false)'/>
    				</td>
    				<td>
    					<select id="pathTypeSelect" onchange="pathTypeSelectChange()">
						  <option value="0">请选择</option>
						  <option value="11">人行道路</option>
						  <option value="12">车行道路</option>
						  <option value="13">船行道路</option>
						  <option value="14">索道</option>
						  <option value="15">滑道</option>
						</select>
    				</td>
    			</tr>
    			<tr>
    				<td><input type="checkbox" checked onchange='changeVisibleOfBackgroundLayer()' id="backgroundId"/></td>
    				<td>背景</td>
    				<td><input type="button" value="创建" onclick='startCreateBackground()'/>
    					<input type="button" value="开始编辑" onclick='startEditBackground()'/>
    					<input type="button" value="结束编辑" onclick='endEditBackground()'/>
    					<input type="button" value="删除" onclick='deleteSelectBackground()'/>
    					<input type="button" value="全选" onclick='selectAllBackground(true)'/>
    					<input type="button" value="清选" onclick='selectAllBackground(false)'/>
    					<input type="button" value="上移" onclick='moveUpOfBackground(true)'/>
    					<input type="button" value="下移" onclick='moveUpOfBackground(false)'/>
    					
    				</td>
    				<td>
    					<select id="backgroundTypeSelect" onchange="backgroundTypeSelectChange()">
						  <option value="0">请选择</option>
						  <option value="1">平地</option>
						  <option value="2">山地</option>
						  <option value="3">水面</option>
						</select>
    				</td>

    			</tr>
    		</tbody>
    		
    	</table>
    </div>
    <div id="tip">
    	<div>longitude：<input type="text" id="lngX" name="lngX" value=""/>&nbsp;latitude：<input type="text" id="latY" name="latY"
                                                                             value=""/></div>
	</div>
    <div class='controlPanel rb'>
      <input type='checkbox' onchange='refresh()' checked name = 'bg'>背景
      <input type='checkbox' onchange='refresh()' checked name = 'road'>道路
      <input type='checkbox' onchange='refresh()' checked name = 'building'>建筑物
      <input type='checkbox' onchange='refresh()' checked name = 'point'>标注
    </div>
    
    <script type="text/javascript" src='http://webapi.amap.com/maps?v=1.3&key=您申请的key值'></script>
    <script type="text/javascript">

    function GetHostString()
    {
         
         var pos = window.location.href.indexOf(":",6);
         var ret = window.location.href.substr(0,pos);
         return ret;
         
    }
    function GetQueryString(name)
    {
         var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
         var r = window.location.search.substr(1).match(reg);
         if(r!=null)return  unescape(r[2]); return null;
    }
    //  全局变量
    var g_host = GetHostString();
    var g_resortid = GetQueryString("resortid");
    var g_lat = 30.5927504277;
    var g_lon = 114.3052418195;
    
    
    // 加载地图
    var map,OverView;
    map = new AMap.Map('mapDiv',{
        resizeEnable:true,
        view:new AMap.View2D({
          center:new AMap.LngLat(g_lon,g_lat),
          zoom:17
        })
    });
    
 	// 地图类型切换
    map.plugin(["AMap.MapType"], function () {
      var type = new AMap.MapType({
        defaultType: 0
      });
      map.addControl(type);
    });
 
  	//使用CSS默认样式定义地图上的鼠标样式
   	map.setDefaultCursor("pointer");
	//    map.setDefaultCursor("url('http://api.amap.com/webapi/static/Images//0.png'),pointer");
  
    // 控制地图各层的显示
    function refresh(){
      var boxes = document.getElementsByTagName('input');
      var features = [];
      for(var i = 0 ;i < boxes.length; i += 1){
        if(boxes[i].checked === true){
          features.push(boxes[i].name);
        }
      }
      map.setFeatures(features);
    }
    
  	//在地图中添加ToolBar插件
  	var toolBar = null;
    map.plugin(["AMap.ToolBar"], function () {
      toolBar = new AMap.ToolBar();
      map.addControl(toolBar);
      toolBar.show()
    });
 
 	// 加载比例尺插件
    var scale;
    map.plugin(["AMap.Scale"], function () {
      scale = new AMap.Scale();
      map.addControl(scale);
      scale.show();
    });
    
    
	 // 加载鹰眼插件
 	var overView;
    map.plugin(["AMap.OverView"], function () {
      overView = new AMap.OverView({
        visible: true
      });
      map.addControl(overView);
    });
    
    //为地图注册click事件获取鼠标点击出的经纬度坐标
     var clickEventListener = map.on( 'click', function(e) {
        document.getElementById("lngX").value = e.lnglat.getLng();
        document.getElementById("latY").value = e.lnglat.getLat();
    });
    
    
    
    
  
// ----------------------------------------------------------------------------------
	// 地图编辑器
  	var mapEditor = new  MapEditor();
  	mapEditor.init(map);
// ----------------------------------------------------------------------------------  	
  	//在地图中添加MouseTool插件
  	var mouseTool = null;
    map.plugin(["AMap.MouseTool"], function() {
    	
    });
  	//添加编辑控件
    var editorTool = null;
    map.plugin(["AMap.PolyEditor"], function() {
    });
/*     	editorTool.open();
    	editorTool.close();
*/

 	
 	
  	// ----------------------------------------------------------------------------------
  	var mapEditor = new  MapEditor();
  	mapEditor.init(map);
  	
 	// 修改"路径层"的可视
    function changeVisibleOfPathLayer(){
    	//  调整界面按钮的显示状态
    	refreshUI();
    	
  		if(mouseTool!=null){
  			mouseTool.close();
  			mouseTool==null;
  		}
  			

    	
 		var v = $("#pathId").is(':checked');
		mapEditor.setVisibleOfPathLayer(v);
		mapEditor.draw();
		
		
    }
    // 修改"路径层"的可视
  	function changeVisibleOfBackgroundLayer(){
  		//  调整界面按钮的显示状态
    	refreshUI();
  		
  		if(mouseTool!=null){
  			mouseTool.close();
  			mouseTool==null;
  		}

  		
 		var v = $("#backgroundId").is(':checked');
 		mapEditor.setVisibleOfBackgroundLayer(v);
 		//mapEditor.draw();
  	}
    // 开始创建道路
    function clickMapObjCallback(f){
    	// 修改内核数据
    	var clickObj = f.target;
    	mapEditor.reverseSelectState(clickObj);
    	
    	// 刷新界面
    	refreshSelectValue();
    }
  	function startCreatePath(){
  		// 复原编辑器
    	if(editorTool!=null){
        	editorTool.close();
        	editorTool = null;    		
    	}
  	
  		mouseTool = new AMap.MouseTool(map);
        mouseTool.polyline(MapCommon.prototype.pathOption);   // 使用鼠标工具绘制多边形
        AMap.event.addListener(mouseTool, "draw", function(e) { // 右键
            //obj属性就是绘制完成的覆盖物对象
            var drawObj = e.obj;
            mapEditor.addPathLayerChild(drawObj);
            
            mouseTool.close();
            mouseTool = null;
            
            AMap.event.addListener(drawObj, 'click', clickMapObjCallback);
        });
  	}
    function startEditPath(){
    	// 复原编辑器
    	if(editorTool!=null){
        	editorTool.close();
        	editorTool = null;    		
    	}
    	
    	var selectObj = mapEditor.getSelectPath();
    	if(selectObj==null){
    		alert(MapCommon.prototype.MSG_MUST_SELECT);
    		return;
    	}
    	
    	editorTool = new AMap.PolyEditor(map, selectObj);
    	editorTool.open();
    }
    function endEditPath(){
    	// 复原编辑器
    	if(editorTool!=null){
        	editorTool.close();
        	editorTool = null;    		
    	}
    		
    }
    
  	function selectAllPath(v){
  		// 复原编辑器
    	if(editorTool!=null){
        	editorTool.close();
        	editorTool = null;    		
    	}
  	
  		// 修改内核数据， 修改界面
  		mapEditor.selectAllPath(v);
  		
  		
  		refreshSelectValue();// 刷新下拉列表
  	}
  	function deleteSelectPath(){
  		// 复原编辑器
    	if(editorTool!=null){
        	editorTool.close();
        	editorTool = null;    		
    	}
  		// 修改内核数据， 修改界面
  		mapEditor.deleteSelectPath();
  	}
  	
  	// 下拉列表变化后的
  	function pathTypeSelectChange(){
  		var type = $('#pathTypeSelect').val();
  		var paths = mapEditor.getAllSelectPath();
  		for(var p=0; p<paths.length; p++){
    		var one = paths[p];
    		var ext = one.getExtData();
    		ext.setType(type);
    		one.setExtData(ext);
  		}  	
  		
  		// 刷新界面
  		mapEditor.refreshColor();
  	}
  	//-------------------------------------------------------
 	// 开始创建背景
 	
  	function startCreateBackground(){
  	// 复原编辑器
    	if(editorTool!=null){
        	editorTool.close();
        	editorTool = null;    		
    	}
  	
  		mouseTool = new AMap.MouseTool(map);
        mouseTool.polygon(MapCommon.prototype.backgroundOption);   // 使用鼠标工具绘制多边形
        AMap.event.addListener(mouseTool, "draw", function(e) { // 右键
            //obj属性就是绘制完成的覆盖物对象
            var drawObj = e.obj;
            mapEditor.addBackgroundLayerChild(drawObj);
            
            mouseTool.close();
            mouseTool = null;
            AMap.event.addListener(drawObj, 'click', clickMapObjCallback);
        });
  	}
  	
  	
  	function startEditBackground(){
    	// 复原编辑器
    	if(editorTool!=null){
        	editorTool.close();
        	editorTool = null;    		
    	}
    	
    	var selectObj = mapEditor.getSelectBackground();
    	if(selectObj==null){
    		alert(MapCommon.prototype.MSG_MUST_SELECT);
    		return;
    	}
    	
    	editorTool = new AMap.PolyEditor(map, selectObj);
    	editorTool.open();
    }
    function endEditBackground(){
    	// 复原编辑器
    	if(editorTool!=null){
        	editorTool.close();
        	editorTool = null;    		
    	}
    		
    }
  	function selectAllBackground(v){
  		// 复原编辑器
    	if(editorTool!=null){
        	editorTool.close();
        	editorTool = null;    		
    	}
  	
  		// 修改内核数据， 修改界面
  		mapEditor.selectAllBackground(v);
  		
  		
  		refreshSelectValue();// 刷新下拉列表
  	}
  	function deleteSelectBackground(){
  		// 复原编辑器
    	if(editorTool!=null){
        	editorTool.close();
        	editorTool = null;    		
    	}
  	
  	
  		// 修改内核数据， 修改界面
  		mapEditor.deleteSelectBackground();
  	}
  	
  	// 下拉列表变化后的
  	function backgroundTypeSelectChange(){
  		var type = $('#backgroundTypeSelect').val();
  		var paths = mapEditor.getAllSelectBackground();
  		for(var p=0;p<paths.length;p++){
    		var one = paths[p];
    		var ext = one.getExtData();
    		ext.setType(type);
    		one.setExtData(ext);
  		}  
  		
  		// 刷新界面
  		mapEditor.refreshColor();
  	}
  	
 // ----------------------------------------------------------------------------------
 	//  调整界面按钮的显示状态
 	function refreshUI(){
    	var v = $("#pathId").is(':checked');
    	var btns = $("#pathId").parent().next().next().children();
    	for(var b=0;b<btns.length;b++){
    		if(v){
    			btns.eq(b).removeAttr("disabled");
    		}else{
    			btns.eq(b).attr('disabled',true);	
    		}
    		 
    	}
    	
    	var v = $("#backgroundId").is(':checked');
    	var btns = $("#backgroundId").parent().next().next().children();
    	for(var b=0;b<btns.length;b++){
    		if(v){
    			btns.eq(b).removeAttr("disabled");
    		}else{
    			btns.eq(b).attr('disabled',true);	
    		}
    		 
    	}
    }
    // 调整下拉列表的选中项
    function refreshSelectValue(){
    	// 路线
    	var paths = mapEditor.getAllSelectPath();
    	var same = true;
    	var type = MapCommon.prototype.OBJECT_TYPE_0;
    	for(var p=0;p<paths.length;p++){
    		var one = paths[p];
    		var ext = one.getExtData();
    		var t = ext.getType();
    		if(p==0){
    			type = t; 
    		}else{
    			if(type!=t){
    				same = false;
    				break;
    			}
    		}
    	}
    	type = same?type:MapCommon.prototype.OBJECT_TYPE_0;
    	$("#pathTypeSelect").val(type);
    	
    	
    	// 背景
    	var paths = mapEditor.getAllSelectBackground();
    	var same = true;
    	var type = MapCommon.prototype.OBJECT_TYPE_0;
    	for(var p=0;p<paths.length;p++){
    		var one = paths[p];
    		var ext = one.getExtData();
    		var t = ext.getType();
    		if(p==0){
    			type = t; 
    		}else{
    			if(type!=t){
    				same = false;
    				break;
    			}
    		}
    	}
    	type = same?type:MapCommon.prototype.OBJECT_TYPE_0;
    	$("#backgroundTypeSelect").val(type);
    	
    }
    //----------------------------------------------------------
    function load(){
    	if( !g_resortid){
    		alert(MapCommon.prototype.MSG_NO_RESORTID);
    		return;
    	}
    	// 切换地图视口
    	$.get(g_host+":8080/etourism/resort/detail/"+g_resortid, function(data){
    		  
    		  
    		  // 坐标转换
    		  var bd = new MapLatLon(data.latitude, data.longitude);
			  var gg = new MapLatLon();
			  CoordinateConvert.prototype.bd_decrypt(bd,gg);
			  
			  g_lat = gg.lat;
    		  g_lon = gg.lon;
    		  
    		  map.setCenter(new AMap.LngLat(g_lon,g_lat));
    		  
    		  addGrids();// 添加网格
    		  
    		  // 尝试加载地图
    		  $.get(g_host+":8080/etourism/resort/lt_getMap?resortid="+g_resortid, function(data){
    			  
    			  if(data==null || !data.hasOwnProperty("data") || data.data.map==null){// 新地图，无旧数据
    				  
    			  }else{
    				  	// 旧地图，尝试加载
    				  	var json = data.data.map
    				  	mapEditor.fromJson(JSON.parse(json));
    			    	mapEditor.draw();
    			    	mapEditor.enableClick(clickMapObjCallback);
    			  }
    			  // 加载行走轨迹
    			  $.get(g_host+":8080/etourism/foottrace/lt_footTraces?resortid="+g_resortid, function(data){
    				  if(data==null || !data.hasOwnProperty("data") || data.data.map==null){// 新地图，无旧数据
        				  
        			  }else{
        				  var jsonOfList = data.data; // 用户轨迹List
        				  mapEditor.footTracesFromJsonStr(jsonOfList);
        				  mapEditor.drawFootTraces(false);
    				  }
    			  });
    			  
    			  // 加载兴趣点
    			  $.get(g_host+":8080/etourism/attractions/"+g_resortid, function(data){
    				  if(data){
    					  for(var i=0;i<data.length;i++){
    						  /* 
    						  t1.id,t1.name,t1.longitude,t1.latitude,t1.soundurl,
    							t3.name as cityName,t1.type type */
    							
    						  // 坐标转换
    						  var one = data[i];
    						  var bd = new MapLatLon(one.latitude, one.longitude);
    						  var gg = new MapLatLon();
    						  CoordinateConvert.prototype.bd_decrypt(bd,gg);
    						  
    						 // http://localhost:8080/mbTravelWeb/mapEditor/icon/2.png
    						  var image = "mapEditor/icon_28/"+one.type+".png"
    						  
    						  var marker = new AMap.Marker({
    						        //复杂图标
    						        icon: new AMap.Icon({
    						            //图标大小
    						            size: new AMap.Size(28, 38),
    						            //大图地址
    						           // image: "http://webapi.amap.com/images/custom_a_j.png",
    						            image:image,
    						            imageOffset: new AMap.Pixel(0, 10)
    						        }),
    						        //在地图上添加点
    						        position: [gg.lon, gg.lat]
    						    });
    							// 设置label标签
    						    marker.setLabel({//label的父div默认蓝框白底右下角显示，样式className为：amap-marker-label
    						        //offset:new AMap.Pixel(50,50),//修改父div相对于maker的位置
    						        content:one.name
    						    });
    						    marker.setMap(map);	

    						    // 记录label
    						    var ext = new MapObjExtData();
    							ext.setLabel(one.name);
    							marker.setExtData(ext);
    							
    						    // 添加到内核
    						    mapEditor.addMarker(marker);
    						    
    						    
    						  
    					  }
    				  }
    			  });
    			  
    		  });
    	});
    }
    load(); // 加载
    
    
 	// 添加网格
    var grid_cell_h = 0.0075;
    var grid_cell_v = 0.0025;
    function addGrids() {
    	// 竖线
    	var lines = [];
    	for(var h=-10;h<10;h++){
    		var lh = g_lon+h*grid_cell_h;
    		lines.push([[lh,-180],[lh,180]]);
    	}
    	//var lineArr = [[g_lon,-180],[g_lon,180]];
    	
    	// 横线
    	for(var v=-10;v<10;v++){
    		var lv = g_lat+v*grid_cell_v;
    		lines.push([[-180,lv],[180,lv]]);
    	}
    	 
        for(var m=0;m<lines.length;m++){
        	var polyline = new AMap.Polyline({
                path: lines[m],          //设置线覆盖物路径
                strokeColor: "#FF0000", //线颜色
                strokeOpacity: 1,       //线透明度
                strokeWeight: 0,        //线宽
                strokeStyle: "solid",   //线样式
                strokeDasharray: [10, 5] //补充线样式
              });
            polyline.setMap(map);
            
            
            mapEditor.addGrid(polyline);// 记录到内核
        	
        }
     }
    // 移动层次
    function moveUpOfPath(isUp){
    	mapEditor.moveUp(isUp, true);
    }
 	// 移动层次
    function moveUpOfBackground(isUp){
    	mapEditor.moveUp(isUp,false);
    }
    
    // 保存
    function saveAll(){
    	var json = mapEditor.toJson();
    	var data = {};
     	data.map = json; 
    	data.resortid = g_resortid; 
    	var data = $.toJSON(data); 
    	$.ajax({
            type: "POST",
            url: g_host+":8080/etourism/resort/lt_addMap",
            data: data,
            contentType:"application/json;charset=utf-8",                       
            success: function(result){
        	    if(result.success==1){
        	    	alert(MapCommon.prototype.MSG_SAVE_SUCCESS);
        	    }else{
        	    	alert(MapCommon.prototype.MSG_SAVE_FAIL);
        	    }
            }
             
        });
    }
    // 加载
    function loadAll(){
    	var json = '{"version":1,"data":{"paths":[{"points":[[114.300619,30.545157,114.300952,30.545397,114.301016,30.545073,114.301317,30.54524]],"ext":{"type":11,"hard":0}}],"backgrounds":[{"points":[[114.300212,30.545194,114.300802,30.545508,114.301982,30.545267,114.301639,30.544787]],"ext":{"type":1,"hard":0}}]}}';
    	mapEditor.fromJson(JSON.parse(json));
    	mapEditor.draw();
    	mapEditor.enableClick(clickMapObjCallback);
    }
	function showAllMarkers(){
		mapEditor.setVisibleOfMarker(true);
	}
	function hideAllMarkers(){
		mapEditor.setVisibleOfMarker(false);
	}
	function showAllMarkersName(){
		mapEditor.setVisibleOfMarkerName(true);
	}
	function hideAllMarkersName(){
		mapEditor.setVisibleOfMarkerName(false);
	}
	
	function showAllGrids(){
		mapEditor.setVisibleOfGrids(true);
	}
	function hideAllGrids(){
		mapEditor.setVisibleOfGrids(false);
	}
	function showAllFootTraces(){
		mapEditor.setVisibleOfFootTraces(true);
	}
	function hideAllFootTraces(){
		mapEditor.setVisibleOfFootTraces(false);
	}
	

    </script>
  </body>
</html>